﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraPrinting;
using DevExpress.XtraTreeList;
using HRM.DICTIONARY.WAITFORM;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HRM.DICTIONARY.DAL
{
    public class Common<T> : ICommon<T> where T :class
    {
        public virtual BaseView BV { get; set; }
        public virtual string ErrMsg { get; set; }
        public virtual DevExpress.XtraGrid.GridControl GC { get; set; }
        public virtual DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView GV { get; set; }
        public virtual DevExpress.XtraGrid.Views.BandedGrid.BandedGridView BGV { get; set; }
        public virtual T currEntity { get; set; }
        public virtual List<String> ValueOfGridViewRow { get; set; }
        public virtual Actions myAction { get; set; }
        public virtual String ColIDName { get; set; }
        public virtual String[] ColIDsName { get; set; }
        public virtual DbSet<T> DbSet { get; set; }
        public virtual DbContext dbEntities { get; set; }
        public ProgressForm progressForm = null;
        public WaitDialogForm dlg = null;

        public Common(DbContext mydbEntities)
        {
            if (mydbEntities == null)
            {
                throw new ArgumentException("Null context");
            }
            this.dbEntities = mydbEntities;
            DbSet = mydbEntities.Set<T>();
            ValueOfGridViewRow = new List<string>();
            myAction = Actions.View;
        }
        
        public virtual List<T> GetList()
        {
            return DbSet.ToList();
        }
        public virtual DataTable GetTable()
        {
            var table = ConvertListToDataTable(DbSet.ToList());
            return table;
        }
        public virtual bool AddCombo(System.Windows.Forms.ComboBox combo, string displayMember, string valueMember, bool isHasAll)
        {
            bool isSuccess = false;
            string isOK = "";
            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    if (isHasAll)
                    {
                        DataRow row = table.NewRow();
                        row[valueMember] = "All";
                        row[displayMember] = "Tất Cả";
                        table.Rows.InsertAt(row, 0);
                    }
                    isOK = TableToComboBox(combo, table, displayMember, valueMember);
                    if (isOK != "OK")
                    {
                        ErrMsg = isOK;
                        isSuccess = false;
                    }
                    isSuccess = true;
                }
            }
            return isSuccess;
        }
        public virtual bool AddComboBoxEdit(DevExpress.XtraEditors.ComboBoxEdit combo, string valueMember)
        {
            bool isSuccess = false;
            var table = GetTable();
            if (valueMember == null || valueMember == "")
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            if (table == null)
            {
                ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                isSuccess = false;
            }
            else
            {
                foreach (DataRow row in table.Rows)
                    combo.Properties.Items.Add(row[valueMember]);
                isSuccess = true;
            }
            return isSuccess;
        }
        public virtual bool AddCheckComboEdit(CheckedComboBoxEdit checkedCombo, string displayMember, string valueMember)
        {
            bool isSuccess = false;

            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    foreach (DataRow row in table.Rows)
                    {
                        var item = new CheckedListBoxItem
                        {
                            Description = row[displayMember].ToString(),
                            CheckState = CheckState.Unchecked,
                            Value = row[valueMember].ToString()
                        };
                        checkedCombo.Properties.Items.Add(item);
                    }
                    isSuccess = true;
                }
            }
            return isSuccess;
        }
        public virtual bool AddGridLookupEdit(GridLookUpEdit gridlookup, string displayMember, string valueMember)
        {
            bool isSuccess = false;
            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    gridlookup.Properties.DataSource = table;
                    gridlookup.Properties.DisplayMember = displayMember;
                    gridlookup.Properties.ValueMember = valueMember;
                    isSuccess = true;
                }
            }
            return isSuccess;
        }
        public virtual bool AddGridLookupEdit(GridLookUpEdit gridlookup, string displayMember, string valueMember, DataTable dt)
        {
            bool isSuccess = false;
            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = dt;
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    gridlookup.Properties.DataSource = table;
                    gridlookup.Properties.DisplayMember = displayMember;
                    gridlookup.Properties.ValueMember = valueMember;
                    isSuccess = true;
                }
            }
            return isSuccess;
        }

        public virtual bool AddRepositoryGridLookupEdit(DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit repositoryItemGridLookUpEdit, string displayMember, string valueMember)
        {
            bool isSuccess = false;
            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    repositoryItemGridLookUpEdit.DataSource = table;
                    repositoryItemGridLookUpEdit.DisplayMember = displayMember;
                    repositoryItemGridLookUpEdit.ValueMember = valueMember;

                    isSuccess = true;
                }
            }
            return isSuccess;
        }
        public virtual bool AddRepositoryGridLookupEdit(DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit repositoryItemGridLookUpEdit, string displayMember, string valueMember, DataTable dt)
        {
            bool isSuccess = false;
            if ((displayMember == "" || displayMember == null) && (valueMember == "" || valueMember == null))
            {
                ErrMsg = "Giá trị truyền vào bị null hoặc rỗng";
                isSuccess = false;
            }
            else
            {
                var table = dt;
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    repositoryItemGridLookUpEdit.DataSource = table;
                    repositoryItemGridLookUpEdit.DisplayMember = displayMember;
                    repositoryItemGridLookUpEdit.ValueMember = valueMember;

                    isSuccess = true;
                }
            }
            return isSuccess;
        }

        public virtual bool AddGridControlFromTable()
        {
            bool isSuccess = false;
            try
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)GC.Views[0];
                    gv.OptionsBehavior.AutoPopulateColumns = true;
                    GC.DataSource = table;
                    gv.BestFitColumns();
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                isSuccess = false;
            }
            return isSuccess;
        }
        public virtual bool AddGridControlFromList()
        {
            bool isSuccess = false;
            try
            {
                var table = GetList();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)GC.Views[0];
                    gv.OptionsBehavior.AutoPopulateColumns = true;
                    GC.DataSource = table;
                    gv.BestFitColumns();
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                isSuccess = false;
            }
            return isSuccess;
        }
        public virtual bool AddGridControlFromList(List<T> listSearch)
        {
            bool isSuccess = false;
            try
            {
                var table = listSearch;
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)GC.Views[0];
                    gv.OptionsBehavior.AutoPopulateColumns = true;
                    GC.DataSource = table;
                    gv.BestFitColumns();
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                isSuccess = false;
            }
            return isSuccess;
        }
        public virtual bool AddTreeListControlFromTable(TreeList tl)
        {
            bool isSuccess = false;
            try
            {
                var table = GetTable();
                if (table == null)
                {
                    ErrMsg = "Không thể lấy dữ liệu từ cơ sở dữ liệu";
                    isSuccess = false;
                }
                else
                {
                    tl.DataSource = table;
                    tl.BestFitColumns();
                    isSuccess = true;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                isSuccess = false;
            }
            return isSuccess;
        }
        public virtual void AddGridExport(XtraUserControl Parentform)
        {
            SaveFileDialog dialog = new SaveFileDialog
            {
                Filter = "Microsoft Excel 97-2003(*.xls)|*.xls|Microsoft Excel 2007(*.xlsx)|*.xlsx|PDF(*.pdf)|*.pdf|Rich Text Format(*.rtf)|*.rtf|Webpage (*.htm)|*.htm",
                FilterIndex = 0
            };
            dialog.ShowDialog();
            if (dialog.FileName != null)
            {
                BV = GV;
                try
                {
                    if (dialog.FilterIndex == 1)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "xls");
                    }
                    else if (dialog.FilterIndex == 2)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "xlsx");
                    }
                    else if (dialog.FilterIndex == 3)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "pdf");
                    }
                    else if (dialog.FilterIndex == 4)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "rtf");
                    }
                    else if (dialog.FilterIndex == 5)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "htm");
                    }
                    if (File.Exists(dialog.FileName) && (XtraMessageBox.Show("Bạn muốn mở tài liệu này không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No))
                    {
                        Process.Start(dialog.FileName);
                    }
                }
                catch (Exception)
                {
                    
                }
            }
        }
        public virtual void AddGridExport(XtraForm Parentform)
        {
            SaveFileDialog dialog = new SaveFileDialog
            {
                Filter = "Microsoft Excel 97-2003(*.xls)|*.xls|Microsoft Excel 2007(*.xlsx)|*.xlsx|PDF(*.pdf)|*.pdf|Rich Text Format(*.rtf)|*.rtf|Webpage (*.htm)|*.htm",
                FilterIndex = 0
            };
            dialog.ShowDialog();
            if (dialog.FileName != null)
            {
                BV = GV;
                try
                {
                    if (dialog.FilterIndex == 1)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "xls");
                    }
                    else if (dialog.FilterIndex == 2)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "xlsx");
                    }
                    else if (dialog.FilterIndex == 3)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "pdf");
                    }
                    else if (dialog.FilterIndex == 4)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "rtf");
                    }
                    else if (dialog.FilterIndex == 5)
                    {
                        this.ExportToEx(Parentform, dialog.FileName, "htm");
                    }
                    if (File.Exists(dialog.FileName) && (XtraMessageBox.Show("Bạn muốn mở tài liệu này không?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No))
                    {
                        Process.Start(dialog.FileName);
                    }
                }
                catch (Exception)
                {

                }
            }
        }
        private void ExportToEx(XtraUserControl Parentform, string filename, string ext)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            if (BV == null)
            {
                MessageBox.Show("Đối tượng kết xuất chưa xác định");
            }
            else
            {
                IPrintingSystem currentPS = new PrintingSystem();
                currentPS.AfterChange += new DevExpress.XtraPrinting.ChangeEventHandler(this.Export_ProgressEx);
                if (ext == "rtf")
                {
                    BV.ExportToRtf(filename);
                }
                if (ext == "pdf")
                {
                    BV.ExportToPdf(filename);
                }
                if (ext == "mht")
                {
                    BV.ExportToMht(filename);
                }
                if (ext == "htm")
                {
                    BV.ExportToHtml(filename, new HtmlExportOptions("utf-8"));
                }
                if (ext == "txt")
                {
                    BV.ExportToText(filename, new TextExportOptions(" ", Encoding.Unicode));
                }
                if (ext == "xls")
                {
                    BV.ExportToXls(filename, new XlsExportOptions(TextExportMode.Value, true));
                }
                if (ext == "xlsOld")
                {
                    BV.ExportToExcelOld(filename);
                }
                if (ext == "xlsx")
                {
                    BV.ExportToXlsx(filename, new XlsxExportOptions(TextExportMode.Value, true));
                }
                currentPS.AfterChange -= new DevExpress.XtraPrinting.ChangeEventHandler(this.Export_ProgressEx);
                Cursor.Current = current;
            }
        }
        private void ExportToEx(XtraForm Parentform, string filename, string ext)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            if (BV == null)
            {
                MessageBox.Show("Đối tượng kết xuất chưa xác định");
            }
            else
            {
                IPrintingSystem currentPS = new PrintingSystem();
                currentPS.AfterChange += new DevExpress.XtraPrinting.ChangeEventHandler(this.Export_ProgressEx);
                if (ext == "rtf")
                {
                    BV.ExportToRtf(filename);
                }
                if (ext == "pdf")
                {
                    BV.ExportToPdf(filename);
                }
                if (ext == "mht")
                {
                    BV.ExportToMht(filename);
                }
                if (ext == "htm")
                {
                    BV.ExportToHtml(filename, new HtmlExportOptions("utf-8"));
                }
                if (ext == "txt")
                {
                    BV.ExportToText(filename, new TextExportOptions(" ", Encoding.Unicode));
                }
                if (ext == "xls")
                {
                    BV.ExportToXls(filename, new XlsExportOptions(TextExportMode.Value, true));
                }
                if (ext == "xlsOld")
                {
                    BV.ExportToExcelOld(filename);
                }
                if (ext == "xlsx")
                {
                    BV.ExportToXlsx(filename, new XlsxExportOptions(TextExportMode.Value, true));
                }
                currentPS.AfterChange -= new DevExpress.XtraPrinting.ChangeEventHandler(this.Export_ProgressEx);
                Cursor.Current = current;
            }
        }
        private void Export_ProgressEx(object sender, DevExpress.XtraPrinting.ChangeEventArgs e)
        {
            if (e.EventName == "ProgressPositionChanged")
            {
                int position = (int)e.ValueOf("ProgressPosition");
                this.progressForm.SetProgressValue(position);
            }
        }

        public virtual T GetById(Object Id)
        {
            return DbSet.Find(Id);
        }
        public virtual long CountAll()
        {
            return (Int64)dbEntities.Set<T>().ToList().Count();
        }
        public virtual bool Insert(T entity)
        {
            try
            {
                var KQ = false;
                if (entity == null)
                    throw new ArgumentNullException("Not found entity");
                T entity1 = dbEntities.Set<T>().Add(entity);
                if (entity1 != null)
                {
                    KQ = true;
                }
                return KQ;
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return false;
            }
        }
        public virtual bool Update(T entity)
        {
            try
            {
                var KQ = false;
                if (entity == null)
                    throw new ArgumentNullException("Not found entity");
                if (dbEntities.Entry(entity) == null)
                {
                    dbEntities.Set<T>().Attach(entity);
                }
                dbEntities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                KQ = true;
                return KQ;
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return false;
            }
        }
        public virtual bool Delete(T entity)
        {
            try
            {
                var KQ = false;
                if (entity == null)
                    throw new ArgumentNullException("Not found entity");
                T entity1 = dbEntities.Set<T>().Remove(entity);
                if (entity1 != null)
                {
                    KQ = true;
                }
                return KQ;
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return false;
            }
        }
        public virtual bool Delete(Object Id)
        {
            T entity = DbSet.Find(Id);
            return Delete(entity);
        }
        public virtual List<T> Where(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            List<T> myList = dbEntities.Set<T>().Where<T>(predicate).ToList();
            return myList;
        }
        public virtual List<T> OrderBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            List<T> myList = dbEntities.Set<T>().OrderBy(predicate).ToList();
            return myList;
        }
        public virtual List<T> Distinct()
        {
            List<T> myList = dbEntities.Set<T>().Distinct<T>().ToList();
            return myList;
        }
        public virtual T FirstElement()
        {
            T currEntity = dbEntities.Set<T>().First(); 
            return currEntity;
        }
        public virtual T LastElement()
        {
            T lastEntity = dbEntities.Set<T>().Last();
            return lastEntity;
        }
        public virtual List<T> Include(string[] collections)
        {
            IQueryable<T> query = dbEntities.Set<T>();
            foreach (var include in collections)
                query = query.Include(include);
            return query.ToList();
        }

        /// <summary>
        /// Trafer data from table to Combobox
        /// </summary>
        /// <param name="combo">System.Window.Forms.Combobox</param>
        /// <param name="table">System.Data.DataTable</param>
        /// <param name="Value">combo.DisplayMember = value</param>
        /// <param name="Key">combo.ValueMember = key</param>
        /// <returns></returns>
        private static string TableToComboBox(System.Windows.Forms.ComboBox combo, DataTable table, string Value, string Key)
        {
            string result = "";
            try
            {
                combo.DataSource = table;
                combo.DisplayMember = Value;
                combo.ValueMember = Key;
                result = "OK";
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }
        public DataTable ConvertListToDataTable<T>(List<T> l_oItems)
        {
            var firstItem = l_oItems.FirstOrDefault();
            if (firstItem == null)
                return new DataTable();

            DataTable oReturn = new DataTable(TypeDescriptor.GetClassName(firstItem));
            object[] a_oValues;
            int i;

            var properties = TypeDescriptor.GetProperties(firstItem);

            foreach (PropertyDescriptor property in properties)
            {
                oReturn.Columns.Add(property.Name, BaseType(property.PropertyType));
            }

            //#### Traverse the l_oItems
            foreach (T oItem in l_oItems)
            {
                //#### Collect the a_oValues for this loop
                a_oValues = new object[properties.Count];

                //#### Traverse the a_oProperties, populating each a_oValues as we go
                for (i = 0; i < properties.Count; i++)
                    a_oValues[i] = properties[i].GetValue(oItem);

                //#### .Add the .Row that represents the current a_oValues into our oReturn value
                oReturn.Rows.Add(a_oValues);
            }

            //#### Return the above determined oReturn value to the caller
            return oReturn;
        }
        private static Type BaseType(Type oType)
        {
            //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
            if (oType != null &&
                oType.IsValueType &&
                oType.IsGenericType &&
                oType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                return Nullable.GetUnderlyingType(oType);
            }

            //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
            return oType;
        }

        #region Hiding
        ///
        ///RowClick Event for GridControl DevExpress
        ///
        //private event RowClickEventHander RowClick;
        //private event RowClickEventHander RowDoubleClick;
        //private delegate void RowClickEventHander(object sender, RowClickEventArgs e);
        ///
        ///GetCellValue from GridControl (DevExpressGridControl)
        ///
        //private object GetCellValue(int RowIndex, int ColumIndex)
        //{
        //    return this.GetCellValue(new RowClickEventArgs(RowIndex, ColumIndex));
        //}
        //private object GetCellValue(int RowIndex, string FieldName)
        //{
        //    return this.GetCellValue(new RowClickEventArgs(RowIndex, FieldName));
        //}
        //private object GetCellValue(RowClickEventArgs e)
        //{
        //    try
        //    {
        //        DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView gbList = GV;
        //        DevExpress.XtraGrid.Columns.GridColumn column = new DevExpress.XtraGrid.Columns.GridColumn();
        //        if (e.ColumnIndex != -1)
        //        {
        //            column = GV.Columns[e.ColumnIndex];
        //        }
        //        else
        //        {
        //            column = GV.Columns[e.FieldName];
        //        }
        //        return GV.GetRowCellValue(e.RowIndex, column);
        //    }
        //    catch(Exception)
        //    {
        //        return null;
        //    }
        //}
        //private object GetCellValue(int Rowindex, DevExpress.XtraGrid.Columns.GridColumn ColIndex)
        //{
        //    return this.GetCellValue(new RowClickEventArgs(Rowindex, ColIndex.ColumnHandle, ColIndex.FieldName));
        //}
        #endregion

        ///
        /// Event inherit for Action Insert, Update, or Delete
        /// 
        public virtual T gbList_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender is DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)
                {
                    DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView view = (DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)sender;
                    //int[] iSelectedRows = GV.GetSelectedRows();
                    //System.Data.DataRow row = GV.GetDataRow(GV.FocusedRowHandle);
                    object ID = GV.GetRowCellValue(GV.FocusedRowHandle, ColIDName);
                    if (ID !=null)
                    {
                        T entity = DbSet.Find(ID);
                        currEntity = entity;
                    }else
                        currEntity = null;
                }
                else
                {
                    //XtraMessageBox.Show("Object is not AdvBandedGridView");
                    currEntity = null;
                }
            }
            catch(Exception ex)
            {
                this.ErrMsg = ex.Message;
                currEntity = null;
            }
            return currEntity;
        }
        public virtual T gbList1_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender is DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)
                {
                    DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView view = (DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)sender;
                    int[] iSelectedRows = GV.GetSelectedRows();
                    object ID = GV.GetRowCellValue(GV.FocusedRowHandle, ColIDName);
                    if (ID != null)
                    {
                        T entity = DbSet.Find(ID.ToString());
                        currEntity = entity;
                    }
                    else
                        currEntity = null;
                }
                else
                {
                    XtraMessageBox.Show("Object is not AdvBandedGridView");
                    currEntity = null;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                currEntity = null;
            }
            return currEntity;
        }
        public virtual T gbListMultipleKey_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender is DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)
                {
                    DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView view = (DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView)sender;
                    //int[] iSelectedRows = GV.GetSelectedRows();
                    //System.Data.DataRow row = GV.GetDataRow(GV.FocusedRowHandle);
                    object[] obj = new object[ColIDsName.Length];
                    for(int i = 0; i< ColIDsName.Length; i++)
                    {
                        obj[i] = GV.GetRowCellValue(GV.FocusedRowHandle, ColIDsName[i]);
                    }
                    if (obj != null)
                    {
                        T entity = DbSet.Find(obj);
                        currEntity = entity;
                    }
                    else
                        currEntity = null;
                }
                else
                {
                    //XtraMessageBox.Show("Object is not AdvBandedGridView");
                    currEntity = null;
                }
            }
            catch (Exception ex)
            {
                this.ErrMsg = ex.Message;
                currEntity = null;
            }
            return currEntity;
        }
        public virtual T gbList_DoubleClick(object sender, EventArgs e)
        {
            return gbList_Click(sender, e);
        }
        public virtual T gbList1_DoubleClick(object sender, EventArgs e)
        {
            return gbList1_Click(sender, e);
        }
        public virtual T gbList_MouseDown(object sender, MouseEventArgs e)
        {
            return gbList_Click(sender, e);
        }
        public virtual T gbList1_MouseDown(object sender, MouseEventArgs e)
        {
            return gbList1_Click(sender, e);
        }
        public virtual T gbList_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            return gbList_Click(sender, e);
        }
        public virtual T gbList1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            return gbList1_Click(sender, e);
        }

        public virtual bool DeleteOnGridView(T entity)
        {
            bool IsSuccess = false;
            if (MessageBox.Show("Bạn có muốn xóa không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
            {
                string str = "";

                #region HidingCode DeleteAll
                //DevExpress.XtraGrid.Views.BandedGrid.AdvBandedGridView gbList = GV;
                //int[] selectedRows = gbList.GetSelectedRows();
                //for (int i = selectedRows.Length; i > 0; i--)
                //{
                //    flag = true;
                //    cellValue = this.GetCellValue(selectedRows[i - 1], ColIDName);
                //    if (cellValue != null)
                //    {
                //        bool KQ = this.Delete(entity);
                //        if (KQ)
                //        {
                //            gbList.DeleteRow(selectedRows[i - 1]);
                //        }
                //        else
                //        {
                //            MessageBox.Show("Thông tin không được xóa\n" + str,
                //                "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //        }
                //    }
                //}
                #endregion

                try
                {
                    if (GV.DataSource != null)
                    {
                        if (entity != null)
                        {
                            bool KQ = this.Delete(entity);
                            if (KQ)
                            {
                                StaticVariable.Save();
                                GV.DeleteRow(GV.FocusedRowHandle);
                                GV.RefreshData();
                                IsSuccess = true;
                            }
                            else
                            {
                                IsSuccess = false;
                                MessageBox.Show("Thông tin không được xóa\n" + str, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                    this.ErrMsg = ex.Message;
                    IsSuccess = false;
                }
            }
            return IsSuccess;
        }
        public virtual bool InsertOnGridView(T entity)
        {
            bool KQ =  this.Insert(entity);
            if (KQ)
            {
                StaticVariable.Save();
            }
            return KQ;
        }
        public virtual bool UpdateOnGridView(T entity)
        {
            bool KQ = this.Update(entity);
            if (KQ)
            {
                StaticVariable.Save();
            }
            return KQ;
        }

        //public virtual void AddRowIntoGridView(List<string> ValueOfRow)
        //{
        //    int focusedRowHandle = GV.FocusedRowHandle;
        //    int indexNewRow = GV.RowCount;
        //    GV.AddNewRow();
        //    GV.FocusedRowHandle = indexNewRow + 1;
        //    focusedRowHandle = GV.FocusedRowHandle;
        //    for (int i = 0; (i < GV.Columns.Count) && (i <= ValueOfRow.Count) && (GV.Columns.Count == ValueOfRow.Count); i++)
        //        GV.SetRowCellValue(focusedRowHandle, GV.Columns[i].Name, ValueOfRow[i].ToString());
        //    GV.UpdateCurrentRow();
        //    GV.RefreshData();
        //}
        //public virtual void AddMutipleRowIntoGridView(List<string> ValueOfMultipleRow)
        //{
        //    int focusedRowHandle = GV.FocusedRowHandle;
        //    if (ValueOfMultipleRow.Count % GV.Columns.Count == 0)
        //    {
        //        int totalRow = ValueOfMultipleRow.Count / GV.Columns.Count;
        //        int indexCurrVal = 0;
        //        int lastIndex = GV.Columns.Count;
        //        List<string> ValueOfRow = null;
        //        for (int i = 0; i < totalRow; i++)
        //        {
        //            ValueOfRow = new List<string>();
        //            for (int j = indexCurrVal; j < lastIndex; j++)
        //            {
        //                ValueOfRow[indexCurrVal] = ValueOfMultipleRow[indexCurrVal].ToString();
        //            }
        //            AddRowIntoGridView(ValueOfRow);
        //            if (lastIndex <= ValueOfMultipleRow.Count)
        //            {
        //                indexCurrVal = lastIndex;
        //                lastIndex += (i + 1) * lastIndex;
        //            }
        //        }
        //        GV.RefreshData();
        //    }
        //}
        public virtual void UpdateRowInGridView(List<string> ValueOfRow)
        {
            int focusedRowHandle = GV.FocusedRowHandle;
            for (int i = 0; (i < GV.Columns.Count) && (i <= ValueOfRow.Count) && (GV.Columns.Count == ValueOfRow.Count); i++)
                GV.SetRowCellValue(focusedRowHandle, GV.Columns[i].Name, ValueOfRow[i].ToString());
            GV.RefreshData();
        }
        public virtual string NewID(string YourSign)
        {
            string Gencode = Guid.NewGuid().ToString();
            //try
            //{
            //    long num = 0;
            //    long maxIndex = this.CountAll();
            //    num = (maxIndex <= 0) ? maxIndex = 1 : maxIndex += 1;
            //    Gencode += YourSign + num.ToString().PadLeft(6, '0');
            //}
            //catch(Exception ex)
            //{
            //    this.ErrMsg = ex.Message;
            //}
            return Gencode;
        }

       
    }
}
